<template>
    <div class="report-mode">
        <div v-if="analyzing" class="loading-state">
            <div class="spinner"></div>
            <h3>正在分析中...</h3>
            <p>已完成 {{ completedCount }} / {{ totalCount }}</p>
            <div class="progress-bar">
                <div class="progress-fill" :style="{ width: progressPercentage + '%' }"></div>
            </div>
        </div>

        <div v-else-if="!currentReport" class="empty-state">
            <div class="empty-icon">📁</div>
            <h3>暂无分析报告</h3>
            <p>请点击右上角"新建分析"开始</p>
        </div>

        <div v-else class="report-content">
             <!-- Overview -->
             <div v-if="activeView === 'overview'" class="overview-dashboard">
                <div class="report-meta">
                    <span class="meta-item">📅 分析时间: {{ formatTime(currentReport.createdAt) }}</span>
                    <span class="meta-item">👤 对象: {{ currentReport.subjectName || '全量数据' }}</span>
                    <span class="meta-item">🔢 算法: {{ currentReport.results.length }} 个</span>
                </div>

                <div class="summary-cards">
                    <div class="card danger">
                        <div class="val">{{ stats.danger }}</div>
                        <div class="lbl">高风险异常</div>
                    </div>
                    <div class="card warning">
                        <div class="val">{{ stats.warning }}</div>
                        <div class="lbl">中风险异常</div>
                    </div>
                    <div class="card info">
                        <div class="val">{{ stats.total }}</div>
                        <div class="lbl">检测条目数</div>
                    </div>
                </div>

                <div class="results-list">
                    <h3>🔍 分析结果详情</h3>
                    <div v-for="result in currentReport.results" :key="result.type" class="result-item" @click="$emit('select-detail', result)">
                        <div class="res-header">
                            <span class="res-title">{{ result.pluginName }}</span>
                            <span class="res-time">{{ result.meta?.duration }}ms</span>
                        </div>
                        <div class="res-summary">
                            {{ getSummary(result) }}
                        </div>
                    </div>
                </div>
             </div>

             <!-- Detail View -->
             <div v-else class="detail-view">
                 <div class="detail-header">
                     <h2>{{ currentDetailResult?.pluginName }}</h2>
                     <button class="btn-secondary" @click="$emit('rerun', activeView)">🔄 重新运行此算法</button>
                 </div>
                 
                 <!-- Render Result Data -->
                 <div class="detail-body">
                    <div v-if="activeView === 'fast_pass'" v-html="renderFastPass(currentDetailResult?.data)"></div>
                    <div v-else-if="activeView === 'funds-analysis'" class="funds-result">
                        <div style="height: 600px; width: 100%;">
                             <RelationshipGraph :data="fundsGraphData" />
                             <p style="font-size:12px; color:#999; margin-top:10px;">
                                共发现 {{ fundsGraphData.nodes.length }} 个节点，{{ fundsGraphData.edges.length }} 条关联
                             </p>
                        </div>
                    </div>
                    <div v-else class="generic-result">
                        <pre>{{ JSON.stringify(currentDetailResult?.data, null, 2) }}</pre>
                    </div>
                 </div>
             </div>
        </div>
      </div>
</template>

<script setup>
import { computed } from 'vue'
import { FastPassAnalyzer } from '@/services/analysis/analyzers/financial/FastPassAnalyzer'
import RelationshipGraph from '@/components/profile/RelationshipGraph.vue'

const props = defineProps({
    analyzing: { type: Boolean, default: false },
    currentReport: { type: Object, default: null },
    activeView: { type: String, default: 'overview' },
    completedCount: { type: Number, default: 0 },
    totalCount: { type: Number, default: 0 }
})

const emit = defineEmits(['select-detail', 'rerun'])

const progressPercentage = computed(() => props.totalCount ? (props.completedCount / props.totalCount) * 100 : 0)

const currentDetailResult = computed(() => {
    if (!props.currentReport) return null
    return props.currentReport.results.find(r => r.type === props.activeView || r.pluginId === props.activeView)
})

const stats = computed(() => {
    if (!props.currentReport) return { danger: 0, warning: 0, total: 0 }
    let total = 0
    let danger = 0
    let warning = 0
    
    props.currentReport.results.forEach(r => {
        const count = Array.isArray(r.data) ? r.data.length : (r.data?.nodes?.length || 0)
        total += count
        if (count > 0) warning++ 
    })
    return { total, warning, danger }
})

const fundsGraphData = computed(() => {
    const raw = currentDetailResult.value?.data
    if (!raw) return { nodes: [], edges: [] }
    
    return {
        nodes: (raw.nodes || []).map(n => ({
            id: n.id || n.name, 
            name: n.name,
            type: n.isTarget ? 'company' : 'person', // Visual hack for styling
            risk_score: n.value 
        })),
        edges: (raw.links || []).map(l => ({
            source: l.source,
            target: l.target,
            weight: l.value
        }))
    }
})

// Formatters
const formatTime = (iso) => new Date(iso).toLocaleString()

const getSummary = (result) => {
    const count = Array.isArray(result.data) ? result.data.length : (result.data?.nodes?.length || 0)
    return `检测到 ${count} 条记录`
}

// Generic Render Helpers
const fastPassRenderer = new FastPassAnalyzer('dummy')
const renderFastPass = (data) => {
    return fastPassRenderer.renderResult(data)
}
</script>

<style scoped>
/* Report Mode */
.report-mode {
    flex: 1;
    padding: 20px;
    overflow-y: auto;
}

.loading-state, .empty-state {
    height: 100%;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    color: #909399;
}

.spinner {
    border: 4px solid #f3f3f3;
    border-top: 4px solid #409eff;
    border-radius: 50%;
    width: 50px;
    height: 50px;
    animation: spin 1s linear infinite;
    margin-bottom: 20px;
}
@keyframes spin { 0% { transform: rotate(0deg); } 100% { transform: rotate(360deg); } }

.progress-bar {
    width: 300px;
    height: 6px;
    background: #ebeef5;
    border-radius: 3px;
    margin-top: 15px;
    overflow: hidden;
}
.progress-fill { height: 100%; background: #67c23a; transition: width 0.3s; }

.report-content {
    background: white;
    border-radius: 8px;
    min-height: 100%;
    box-shadow: 0 2px 12px rgba(0,0,0,0.05);
    display: flex;
    flex-direction: column;
}

.overview-dashboard { padding: 30px; }
.report-meta { margin-bottom: 30px; display: flex; gap: 30px; color: #606266; font-size: 14px; }
.summary-cards { display: grid; grid-template-columns: repeat(3, 1fr); gap: 20px; margin-bottom: 40px; }
.card { padding: 20px; border-radius: 8px; text-align: center; }
.card.danger { background: #fef0f0; color: #f56c6c; }
.card.warning { background: #fdf6ec; color: #e6a23c; }
.card.info { background: #f4f4f5; color: #909399; }
.card .val { font-size: 32px; font-weight: bold; }
.card .lbl { margin-top: 5px; font-size: 14px; opacity: 0.8; }

.result-item {
    background: #fcfcfc;
    border: 1px solid #ebeef5;
    padding: 15px;
    border-radius: 4px;
    margin-bottom: 10px;
    cursor: pointer;
    transition: all 0.2s;
}
.result-item:hover { border-color: #c6e2ff; transform: translateX(5px); }
.res-header { display: flex; justify-content: space-between; margin-bottom: 5px; }
.res-title { font-weight: bold; color: #303133; }
.res-time { font-size: 12px; color: #909399; }
.res-summary { font-size: 13px; color: #606266; }

.detail-view { padding: 30px; }
.detail-header { border-bottom: 1px solid #ebeef5; padding-bottom: 15px; margin-bottom: 20px; display: flex; justify-content: space-between; }
.btn-secondary { background: white; border: 1px solid #dcdfe6; padding: 6px 15px; border-radius: 4px; cursor: pointer; }

.json-viewer {
    background: #282c34;
    color: #abb2bf;
    padding: 15px;
    border-radius: 4px;
    overflow: auto;
}
</style>
